package com.example.admin.controller;

import com.example.admin.exception.BusinessException;
import com.example.admin.payload.request.LoginRequest;
import com.example.admin.payload.request.ResetPasswordRequest;
import com.example.admin.payload.request.SignupRequest;
import com.example.admin.payload.response.JwtResponse;
import com.example.admin.payload.response.MessageResponse;
import com.example.admin.service.AuthService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private AuthService authService;

    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
        JwtResponse jwtResponse = authService.authenticateUser(loginRequest);
        return ResponseEntity.ok(jwtResponse);
    }

    @PostMapping("/signup") 
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
        try {
            authService.registerUser(signUpRequest);
            return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
        } catch (BusinessException e) {
            throw e; // 让全局异常处理器处理
        } catch (Exception e) {
            throw new BusinessException("Registration failed: " + e.getMessage());
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logoutUser() {
        authService.logout();
        return ResponseEntity.ok(new MessageResponse("Logout successful!"));
    }

    @PostMapping("/refresh-token")
    public ResponseEntity<?> refreshToken(@Valid @RequestBody String refreshToken) {
        try {
            JwtResponse jwtResponse = authService.refreshToken(refreshToken);
            return ResponseEntity.ok(jwtResponse);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(new MessageResponse(e.getMessage()));
        }
    }

    @PostMapping("/reset-password")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> resetPassword(
            @Valid @RequestBody ResetPasswordRequest resetPasswordRequest) {
        authService.resetPassword(
                resetPasswordRequest.getEmail(), 
                resetPasswordRequest.getNewPassword());
        return ResponseEntity.ok(new MessageResponse("Password reset successfully"));
    }
}
